package cn.org.donald.util;

import cn.org.donald.security.util.JwtUtil;
import cn.org.donald.security.util.MD5Util;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.springframework.util.DigestUtils;

import java.security.NoSuchAlgorithmException;
import java.util.Date;

/**
 * @author: Donald
 * @since: 2021-03-16 22:03:22
 **/
public class CryPtoUtil {

    /**签名证书*/
    private static final String sign = "!1qaz.(lq";

    /**发行者*/
    private static final String issuer = "Donald";

    /**加密类型*/
    private static final Algorithm algorithm = Algorithm.HMAC256(sign);


    public static String getAuthorization(String username ,Long uid, Long expiresTimeMillis) {
        // encoding
        Date date = new Date(System.currentTimeMillis() + expiresTimeMillis);
        JWTCreator.Builder builder = JWT.create()
                .withIssuer(issuer)
                .withExpiresAt(date)
                .withClaim("username",username)
                .withClaim("uid",uid);
        return JwtUtil.encodedJWT(builder, algorithm);
    }

    /**
     * 验证authorization是否正确,通过得到解密后的DecodeJWT
     * @param authorization 前端请求头携带的token
     * @return {@link DecodedJWT}
     */
    public static DecodedJWT verifyAuthorization(String authorization) {
        return JwtUtil.decodedJWT(authorization, algorithm);
    }

    public static String getSalt() {
        return MD5Util.getSalt();
    }

    public static String getEncodedText(String text, String salt) throws NoSuchAlgorithmException {
        return MD5Util.getMD5Encode(text,salt);
    }


    /**
     * 获取简单的md5加密
     * @param context 明文
     * @return md5加密后的字符
     */
    public static String getMD5(String context) {
        return DigestUtils.md5DigestAsHex(context.getBytes());
    }
}
